package org.web.ssm.interceptors;

import com.alibaba.druid.filter.AutoLoad;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.web.ssm.exception.UserException;
import org.web.ssm.model.User;
import org.web.ssm.service.IUserService;
import org.web.ssm.service.wechatService.IWechatService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by LUOLIANG on 2016/6/7.
 * 此拦截器用于拦截未注册用户打开任何一项应用跳转到登录页面
 */
public class WechatLoginInterceptor implements HandlerInterceptor {
    private Logger logger = LogManager.getLogger(WechatLoginInterceptor.class);
    @Autowired
    private IWechatService wechatService;
    @Autowired
    private IUserService userService;

    //返回值:表示是否需要拦截当前的请求        false：请求将被终止  true：请求将被执行
    //handler表示被拦截的对象
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("prehandle方法");

        //获取参数code
        //code说明 ： code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
        String code = request.getParameter("code");
        String redirecturl = request.getParameter("state");

        //通过code获取openid，每个用户都不同
        String openid = wechatService.getOpenid(code);
        logger.info("获取到的openid:" + openid);

        User user = new User();
        try {
            user = userService.getUserByOpenid(openid);
        } catch (UserException e) {
            logger.error("错误信息：" + e.getMessage());
            return false;
        }

        if (user == null) {
            request.getRequestDispatcher("/index/wechat/login").forward(request, response);

            //openid存入cookie
            Cookie cookie = new Cookie("openid", openid);
            response.addCookie(cookie);

            return false;
        } else if (user != null && !user.isLoginstate()) {
            //跳转到登录页面
            request.getRequestDispatcher("/index/wechat/login").forward(request, response);

            return false;
        } else {
            request.getSession().setAttribute("currUser", user);
            response.sendRedirect("/CounterDrops/index/wechat/" + redirecturl);

            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle方法");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion方法");
    }
}
